package utils;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;

import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @program: ocr_auto_app
 * @description:
 * @author: YB
 * @create: 2022-08-08 14:15
 **/
public class OCRUtils {
    public static String DEFAULT_LANG="chi_sim";
    public static String DATA_PATH="D:/temp/test_data/";

    /**
     * 根据图片文件进行识别
     *
     * @param imageFile 图片文件
     * @param lang 指定语言库
     * @return 识别文本信息
     */
    public static String doOCRFromFile(File imageFile, String lang) throws Exception {
        ITesseract instance = new Tesseract();
        instance.setDatapath(DATA_PATH); //指定语言库目录
        instance.setVariable("user_defined_dpi", "96");
//        instance.setTessVariable("user_defined_dpi", "300");
        instance.setLanguage(lang);
        String result = instance.doOCR(imageFile);
        return result;
    }

    public static String doOCRFromFile(File imageFile) throws Exception {
        return doOCRFromFile(imageFile,DEFAULT_LANG);
    }

    /**
     * 根据图片流进行识别
     */
    public static String doOCRFromImgBuffer(BufferedImage bufferedImage, String lang) throws Exception {
        ITesseract instance = new Tesseract();
        instance.setDatapath(DATA_PATH);
        instance.setTessVariable("user_defined_dpi", "300");
        instance.setLanguage(lang);
        String result = instance.doOCR(bufferedImage);

        return result;
    }

    public static String doOCRFromImgBuffer(BufferedImage bufferedImage) throws Exception {
        return doOCRFromImgBuffer(bufferedImage,DEFAULT_LANG);
    }
}
